/*
 * Util.java
 *
 * Created on 10 September 2006, 7:31
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package fasea.utils;

import fasea.model.IndexingFolder;
import fasea.model.IndexingFolderList;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author gvasil
 * @author lars-wolfram
 */
public class FileUtil {

    /**
     * Deletes all files and subdirectories under dir. Returns true if all
     * deletions were successful. If a deletion fails, the method stops
     * attempting to delete and returns false.
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir.delete();
    }

    public static File createTempDir() {
        final String baseTempPath = System.getProperty("java.io.tmpdir");

        Random rand = new Random();
        int randomInt = 1 + rand.nextInt();

        File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
        while (tempDir.exists() == true) {
            randomInt++;
            tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
        }

        tempDir.mkdir();

        return tempDir;
    }

    /**
     * Converts the specified long number to a human-readable form.
     */
    public static String adjustSize(long b) {
        String str;
        long g = 0, m = 0, k = 0;

        if (b == 0) {
            return "";
        }

        if (b > 1073741824) {
            g = b / 1073741824;
            b -= g * 1073741824;
            str = g + " GB";
        } else if (b > 1048576) {
            m = b / 1048576;
            b -= m * 1048576;
            str = m + " MB";
        } else if (b > 1024) {
            k = b / 1024;
            b -= k * 1024;
            str = k + " KB";
        } else {
            str = b + " bytes";
        }

        return str;
    }

    public static void hideFile(File f)
            throws InterruptedException, IOException {
        // XXX TODO: make it compliant with linux.
        String os = System.getProperty("os.name").toLowerCase();

        if (os.indexOf("windows") >= 0) {
            // win32 command line variant
            Process p = Runtime.getRuntime().exec("attrib +h " + f.getPath());
            p.waitFor();
        }
    }

    public static boolean matchIndexingFolderSettings(File f, IndexingFolderList dirs) {
        //XXX TODO: optimize it (and check if correct!)
        try {
            String filePath = f.getCanonicalPath();
            for (IndexingFolder dir : dirs) {
                String dirPath = dir.getIndexingFolder().getCanonicalPath();
                if (dirPath.length() > filePath.length()) {
                    continue;
                }
                String filePath_sub = filePath.substring(0, dirPath.length());
                assert (filePath_sub.length() == dirPath.length());
                if (filePath_sub.equals(dirPath) && matchExtension(FilenameUtils.getExtension(filePath).toLowerCase(), dir.getFileExtensionRestrictions())) {
                    return true;
                }
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }
    
    private static boolean matchExtension(String extension, List<String> possibleExtensions){
        return possibleExtensions.contains(extension);
    }

    /**
     * Returns the size of file
     * <code>file</code> in bytes. If
     * <code>file</code> is a directory, the method returns the summary of all
     * the files contained.
     *
     * @param file A file or directory.
     * @return The size of file
     * <code>file</code> in bytes.
     */
    public static long getFileSize(File file) {
        if (file.isDirectory()) {
            return FileUtils.sizeOfDirectory(file);
        } else {
            return file.length();
        }
    }

    /**
     * Check if the file
     * <code>file</code> is a directory or not. If the file
     * <code>file</code> is a MacOS-Application, this Methode will return <code>false</code> too.
     *
     * @param file
     * @return true if the file <code>file</code> is a directory, false if the file <code>file</code> is a MacOS-Application or a file.
     */
    public static boolean isDirectory(File file) {
        if(file.isDirectory() && !isMacOSApplication(file)){
            return true;
        }else{
            return false;
        }
    }
    
    private static boolean isMacOSApplication(File file){
        if(file.isDirectory() && FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("app")){
            return true;
        }else{
            return false;
        }
    }
}
